//
// Created by yukunlin on 2016/9/3.
//

#include "least_sqr_line_fit.h"

least_sqr_line_fit::least_sqr_line_fit () {
    k = 0.0;
    b = 0.0;
}

double least_sqr_line_fit::sum(vector<double> data)
{
    double sum = 0;
    for (size_t i=0; i<data.size(); i++)
        sum += data[i];
    return sum;
}

double least_sqr_line_fit::dot(vector<double> x, vector<double> y)
{
    assert (x.size()==y.size());
    double sum = 0;
    for (size_t i=0; i<x.size(); i++)
        sum += x[i]*y[i];
    return sum;
}
void least_sqr_line_fit::fit (vector<double> y)
{
    if (y.size()==0) {
        return;
    } else if (y.size()==1) {
        k = 0.0;
        b = y[0];
    } else {
        vector<double> x (y.size());
        for (size_t i=0; i<x.size(); i++)
            x[i] = (double)i;
        fit (x,y);
    }
}

void least_sqr_line_fit::fit (vector<double> x, vector<double> y)
{
    double x_sum = sum(x);
    double y_sum = sum(y);
    double x_dot_x = dot(x,x);
    double x_dot_y = dot(x,y);
    k = ( x_dot_y * x.size() - x_sum * y_sum)/( x_dot_x * x.size() - x_sum * x_sum );
    b = (y_sum - k * x_sum)/x.size();
}

double least_sqr_line_fit::guess (double x)
{
    return k*x + b;
}
